<!DOCTYPE html>
<html lang="zh-cn">
    <head>
        <meta charset="UTF-8">
        <title>更新页面</title>
        <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css" />
        <link rel="stylesheet" href="/app/admin/component/jsoneditor/css/jsoneditor.css" />
        <link rel="stylesheet" href="/app/admin/admin/css/reset.css" />
        <style>
            .selected_class{
                box-shadow: 3px 3px 6px rgba(85, 154, 227, 0.4);
                border: 2px solid #2d8cf0;
            }
            .ellipsis {
                overflow: hidden; /* 确保超出容器的文本被隐藏 */
                white-space: nowrap; /* 确保文本在一行内显示 */
                text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
            }
        </style>
    </head>
    <body>

        <form class="layui-form">

            <div class="mainBox">
                <div class="main-container mr-5">
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 46%">
                            <label class="layui-form-label">内容分段：</label>
                            <div class="layui-input-block">
                                <textarea name="content" class="layui-textarea" rows="4" cols="25"></textarea>
                            </div>
                        </div>
                        <div class="layui-form-item"  style="width: 46%">
                            <label class="layui-form-label">AI指令：</label>
                            <div class="layui-input-block">
                                <tip style="color: red;font-size: 12px;">@content 作为内容替换</tip>
                                <textarea name="prompt_ai_command" class="layui-textarea" rows="4"  cols="25"></textarea>
                            </div>
                        </div>
                    </div>
                    <!--<div class="layui-form-item">-->
                        <!--<label class="layui-form-label"></label>-->
                        <!--<button type="button" class="pear-btn pear-btn-primary pear-btn-md"  lay-submit="" lay-filter="regenerate_analyze_content">-->
                            <!--生成中文描述-->
                        <!--</button>-->
                    <!--</div>-->
                    <!--<div style="display: flex;flex-direction: row;align-items: center">-->
                        <!--<div class="layui-form-item" style="width: 46%">-->
                            <!--<label class="layui-form-label">中文描述：</label>-->
                            <!--<div class="layui-input-block">-->
                                <!--<textarea name="analyze_content" class="layui-textarea" rows="4" cols="25"></textarea>-->
                            <!--</div>-->
                        <!--</div>-->
                        <!--<div class="layui-form-item"  style="width: 46%">-->
                            <!--<label class="layui-form-label">AI指令：</label>-->
                            <!--<div class="layui-input-block">-->
                                <!--<tip style="color: red;font-size: 12px;">@content 作为内容替换</tip>-->
                                <!--<textarea name="prompt_ai_command" class="layui-textarea" rows="4"  cols="25"></textarea>-->
                            <!--</div>-->
                        <!--</div>-->
                    <!--</div>-->
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md"  lay-submit="" lay-filter="regenerate_prompt">
                            生成英文描述
                        </button>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md ai_session" style="margin-left: 20px;">
                            AI会话
                        </button>
                    </div>
                    <!--<div class="layui-form-item">-->
                        <!--<label class="layui-form-label">模型风格：</label>-->
                        <!--<div class="layui-input-block model_html"  style="display: flex;flex-direction: row;align-items: center">-->
                            <!--<div class="model_click"  data-id="1" style="width: 100px;height: 120px;margin-right: 20px;">-->
                                <!--<img src="https://ai-video-1320718644.cos.ap-guangzhou.myqcloud.com/video/local/stable_diffusion_image/20240513/png/0b52503b7725942befdf.png" style="width: 100px;height: 100px;">-->
                                <!--<div>实打实大苏打</div>-->
                            <!--</div>-->
                        <!--</div>-->
                        <!--<input type="hidden" name="modelid" value="">-->
                    <!--</div>-->
                    <!--<div class="layui-form-item">-->
                        <!--<label class="layui-form-label">人物角色：</label>-->
                        <!--<div class="layui-input-block role_html"  style="display: flex;flex-direction: row;align-items: center;flex-wrap: wrap;">-->
                            <!--<div class="role_click"  data-id="1" style="width: 100px;height: 120px;margin-right: 20px;">-->
                                <!--<img src="https://ai-video-1320718644.cos.ap-guangzhou.myqcloud.com/video/local/stable_diffusion_image/20240513/png/0b52503b7725942befdf.png" style="width: 100px;height: 100px;">-->
                                <!--<div>实打实大苏打</div>-->
                            <!--</div>-->
                        <!--</div>-->
                        <!--<input type="hidden" name="roleids" value="">-->
                    <!--</div>-->
                    <div class="layui-form-item">
                        <label class="layui-form-label">描述标签：</label>
                        <div class="layui-input-block tags_html"  style="display: flex;flex-direction: row;align-items: center;flex-wrap: wrap;">
                            <button  type="button" class="layui-btn layui-btn-radius layui-btn-normal select_tags" data-id="1">标签1</button>
                            <button  type="button" class="layui-btn layui-btn-radius layui-btn-normal select_tags" data-id="1">标签1</button>
                        </div>
                    </div>
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 95%">
                            <label class="layui-form-label">英文描述：</label>
                            <div class="layui-input-block">
                                <textarea name="prompt" id="prompt" class="layui-textarea" rows="4" cols="100"  style="width: 100%"></textarea>
                            </div>
                        </div>
                    </div>
                    <div style="display: flex;flex-direction: row;align-items: center">
                        <div class="layui-form-item" style="width: 95%">
                            <label class="layui-form-label">多人描述：</label>
                            <div class="layui-input-block">
                                <textarea name="more_people_prompt" id="more_people_prompt" class="layui-textarea" rows="4" cols="100"  style="width: 100%"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item" style="display: flex;flex-direction: row;">
                        <div style="display: flex;flex-direction: column;">
                            <label class="layui-form-label">AI图像指令</label>
                            <button type="button" class="pear-btn pear-btn-primary pear-btn-md edit_ai_image_command" style="width: 100px;">编辑指令</button>
                        </div>
                        <div style="width: 100%;margin-left: 5px;">
                            <input type="hidden" name="ai_image_command_id" />
                            <input type="hidden" name="ai_image_command_data" />
                            <textarea name="ai_image_command" class="layui-textarea" rows="15" cols="100" onblur="ai_image_command_change()" style="width: 100%"></textarea>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label"></label>
                        <button type="button" class="pear-btn pear-btn-primary pear-btn-md"  lay-submit="" lay-filter="regenerate_image">
                            生成AI图片
                        </button>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">预览图片：</label>
                        <div class="layui-input-block ai_image_html"  style="display: flex;flex-direction: row;align-items: center">

                        </div>
                    </div>
                </div>
            </div>

            <div class="bottom">
                <div class="button-container">
                    <button type="submit" class="pear-btn pear-btn-primary pear-btn-md" lay-submit="" lay-filter="save">
                        提交
                    </button>
                    <!--<button type="reset" class="pear-btn pear-btn-md">-->
                        <!--重置-->
                    <!--</button>-->
                </div>
            </div>

        </form>

        <script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
        <script src="/app/admin/component/pear/pear.js"></script>
        <script src="/app/admin/component/jsoneditor/jsoneditor.js"></script>
        <script src="/app/admin/admin/js/permission.js"></script>
        <script src="/app/admin/admin/js/functions.js"></script>
        <script src="/app/admin/admin/js/md5.js"></script>
        
        <script>
            // let textarea = document.getElementById('prompt');
            // let savedSelectionStart;
            // let savedSelectionEnd;
            //
            // // 当内容被选中时保存位置
            // textarea.addEventListener('select', function() {
            //     savedSelectionStart = textarea.selectionStart;
            //     savedSelectionEnd = textarea.selectionEnd;
            //     // console.log(savedSelectionStart+'-'+savedSelectionEnd)
            // });

            let roleids = [];
            let roleData = [];
            let tagsData = [];
            let planid = 0;

            // 相关接口
            const PRIMARY_KEY = "id";
            const PRIMARY_KEY_VALUE = layui.url().search[PRIMARY_KEY];
            const SELECT_API = "/app/admin/plan/part/select" + location.search;
            const UPDATE_API = "/app/admin/plan/part/update";
            const AI_REGENERATE_API = "/app/admin/plan/part/airegenerate";
            const PROGRESS_API = "/app/admin/index/getaiimageresult";
            const AI_IMAGE_UPDATE_URL =  "/app/admin/plan/index/editaiimagecommand";
            const AI_IMAGE_UPDATE_API =  "/app/admin/plan/index/editaiimagecommand";
            const AI_SESSION_URL =  "/app/admin/plan/part/aisession";

            // 获取数据库记录
            layui.use(["form", "util", "popup", "xmSelect"], function () {
                $ = layui.$;
                $.ajax({
                    url: SELECT_API,
                    dataType: "json",
                    async:true,
                    headers: get_header({"id":PRIMARY_KEY_VALUE}),
                    success: function (res) {
                        
                        // 给表单初始化数据
                        layui.each(res.data[0], function (key, value) {
                            let obj = $('*[name="'+key+'"]');
                            if (key === "password") {
                                obj.attr("placeholder", "不更新密码请留空");
                                return;
                            }
                            if (typeof obj[0] === "undefined" || !obj[0].nodeName) return;
                            if (obj[0].nodeName.toLowerCase() === "textarea") {
                                obj.val(value);
                            } else {
                                obj.attr("value", value);
                                obj[0].value = value;
                            }
                        });
                        planid = res.data[0]['planid'];

                        let html = '';
                        layui.$.each([1,2,3,4],function (i,v) {
                            if(res.data[0]['ai_images'+v]){
                                var imgObj = new Image();                    //新建一个图片对象
                                imgObj.src = res.data[0]['ai_images'+v];                            //将图片的src属性赋值给新建图片对象的src
                                imgObj.onload = function () {
                                    var size =  new Array(imgObj.width, imgObj.height);

                                    size[1] = parseInt(200/size[0]*size[1])
                                    html +='<img src="'+res.data[0]['ai_images'+v]+'" onclick="open_image(this);" style="width: 200px;height: '+size[1]+'px;margin-right: 20px;">';
                                    html +='<input type="hidden" name="ai_images'+v+'" value="'+res.data[0]['ai_images'+v]+'">';
                                    layui.$('.ai_image_html').html(html);
                                }
                            }
                        })

                        layui.$.ajax({
                            url: "/app/admin/image/index/select?limit=1000&status=1",
                            dataType: "json",
                            async:true,
                            headers: get_header({"status":"1"}),
                            success: function (res2) {
                                let html = '';

                                layui.$.each(res2.data,function (i,v) {
                                    let selected = '';
                                    if(v.id==res.data[0]['modelid']){
                                        selected = 'selected_class';
                                    }
                                    html += ' <div class="model_click '+selected+'" data-id="'+v.id+'" style="width: 100px;height: 120px;margin-right: 20px;">\n' +
                                        '           <img src="'+v.image+'" style="width: 100px;height: 100px;" title="'+v.model+'">\n' +
                                        '           <div class="ellipsis">'+v.name+'</div>\n' +
                                        '  </div>';
                                })
                                layui.$('.model_html').html(html);
                                if (res2.code) {
                                    layui.popup.failure(res2.msg);
                                }
                            }
                        });

                        roleids = res.data[0]['roleids'];
                        layui.$.ajax({
                            url: "/app/admin/plan/role/select?limit=1000&status=1&planid="+planid,
                            dataType: "json",
                            async:true,
                            headers: get_header({"status":"1","planid":planid}),
                            success: function (res2) {
                                let html = '';

                                roleData = res2.data;
                                layui.$.each(res2.data,function (i,v) {
                                    let selected = '';
                                    if(roleids.indexOf(String(v.id))>-1){
                                        selected = 'selected_class';
                                    }
                                    html += ' <div class="role_click '+selected+'" data-id="'+v.id+'" style="width: 100px;height: 120px;margin-right: 20px;">\n' +
                                        '           <img src="'+v.ai_images+'" style="width: 100px;height: 100px;" title="'+v.name+'">\n' +
                                        '           <div class="ellipsis">'+v.name+'</div>\n' +
                                        '  </div>';
                                })
                                layui.$('.role_html').html(html);
                                if (res2.code) {
                                    layui.popup.failure(res2.msg);
                                }
                            }
                        });
                        layui.$('input[name="roleids"]').val(roleids.join(','))

                        layui.$('.edit_ai_image_command').click(function () {
                            layer.open({
                                type: 2,
                                title: "编辑AI图像指令",
                                shade: 0.1,
                                maxmin: true,
                                area: ["95%", "100%"],
                                content: AI_IMAGE_UPDATE_URL
                            });
                        })

                        layui.$.ajax({
                            url: "/app/admin/plan/prompttags/select?limit=1000&status=1&select=1&planid="+planid,
                            dataType: "json",
                            async:true,
                            headers: get_header({"status":"1","select":"1","planid":planid}),
                            success: function (res2) {
                                let html = '';

                                tagsData = res2.data;
                                layui.$.each(res2.data,function (i,v) {
                                    html += ' <button  type="button" class="layui-btn layui-btn-radius select_tags" data-prompt="'+compile(v['prompt'])+'" title="'+v['prompt']+'" style="margin-bottom: 5px;">'+v['name']+'</button>';
                                })
                                layui.$('.tags_html').html(html);
                                if (res2.code) {
                                    layui.popup.failure(res2.msg);
                                }
                            }
                        });

                        // ajax返回失败
                        if (res.code) {
                            layui.popup.failure(res.msg);
                        }
                        
                    }
                });

                $('.model_html').delegate('.model_click','click',function () {
                    $('.model_click').removeClass('selected_class');
                    $(this).addClass('selected_class');
                    $('input[name="modelid"]').val($(this).data('id'));
                    //console.log($(this).data('id'));
                })

                $('.role_html').delegate('.role_click','click',function () {
                    let roleid = String($(this).data('id'));
                    let ishas = false;
                    layui.$.each(roleids,function (i,v) {
                        if(v==roleid){
                            ishas = true;
                            roleids.splice(i,1);
                        }
                    })
                    if(ishas==false){
                        roleids.push(roleid);
                    }

                    let tempIds = [];
                    layui.$.each(roleids,function (i,v) {
                        tempIds.push(v);
                    })
                    roleids = tempIds

                    let html = '';
                    layui.$.each(roleData,function (i,v) {
                        let selected = '';
                        let roleid = String(v.id);
                        if(roleids.indexOf(roleid)>-1){
                            selected = 'selected_class';
                        }
                        html += ' <div class="role_click '+selected+'" data-id="'+roleid+'" style="width: 100px;height: 120px;margin-right: 20px;">\n' +
                            '           <img src="'+v.ai_images+'" style="width: 100px;height: 100px;" title="'+v.name+'">\n' +
                            '           <div class="ellipsis">'+v.name+'</div>\n' +
                            '  </div>';
                    })
                    layui.$('.role_html').html(html);
                    layui.$('input[name="roleids"]').val(roleids.join(','))
                })

                $('.tags_html').delegate('.select_tags','click',function () {
                    let prompt = uncompile($(this).data('prompt'));
                    const dom = document.createElement("input");
                    dom.value = prompt;
                    document.body.appendChild(dom);
                    dom.select();
                    document.execCommand("copy");
                    document.body.removeChild(dom);
                    layer.msg("已复制到粘贴板",{time:1000});

                    // if(savedSelectionEnd===undefined){
                    //     layer.msg('请选择要插入标签位置',{"icon":2,"time":1000});
                    //     return false;
                    // }
                    // let content = layui.$('#prompt').val();
                    // let deforeContent = content.substring(0,savedSelectionEnd);
                    // let afterContent = content.substring(savedSelectionEnd);
                    // let contentVal = deforeContent+' '+prompt+' '+afterContent;
                    // //console.log(content,' ------------- ',contentVal,savedSelectionEnd,prompt);
                    // layui.$('#prompt').val(contentVal);
                    // savedSelectionEnd = undefined;
                });
            });

            //提交事件
            layui.use(["form", "popup","loading"], function () {
                layui.form.on("submit(save)", function (data) {
                    data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];
                    let loading = layer.load();
                    layui.$.ajax({
                        url: UPDATE_API,
                        type: "POST",
                        dateType: "json",
                        data: data.field,
                        async:true,
                        headers: get_header(data.field),
                        success: function (res) {
                            layer.close(loading);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                parent.refreshTable();
                                parent.layer.close(parent.layer.getFrameIndex(window.name));
                            });
                        }
                    });
                    return false;
                });

                layui.form.on("submit(regenerate_analyze_content)", function (data) {
                    data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];
                    data.field['type'] = 'regenerate_analyze_content';
                    //let loading = layer.load(2);
                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: data.field,
                        async:true,
                        headers: get_header(data.field),
                        success: function (res) {
                            layui.loading.loadRemove(1);
                            //layer.close(loading);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                layui.$('textarea[name="analyze_content"]').val(res.data.data);
                            });
                        },
                        error:function () {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                    return false;
                });

                layui.form.on("submit(regenerate_prompt)", function (data) {
                    data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];
                    data.field['type'] = 'regenerate_prompt';
                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: data.field,
                        async:true,
                        headers: get_header(data.field),
                        success: function (res) {
                            layui.loading.loadRemove(1);
                            if (res.code) {
                                return layui.popup.failure(res.msg);
                            }
                            return layui.popup.success("操作成功", function () {
                                layui.$('textarea[name="prompt"]').val(res.data.data);
                            });
                        },
                        error:function () {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                    return false;
                });

                layui.form.on("submit(regenerate_image)", function (data) {
                    data.field[PRIMARY_KEY] = layui.url().search[PRIMARY_KEY];
                    data.field['type'] = 'regenerate_image';
                    let loadIndex = layui.loading.Load(1, "生成中...");
                    layui.$.ajax({
                        url: AI_REGENERATE_API,
                        type: "POST",
                        dateType: "json",
                        data: data.field,
                        async:true,
                        headers: get_header(data.field),
                        success: function (res) {
                            if (res.code) {
                                layui.loading.loadRemove(1);
                                return layui.popup.failure(res.msg);
                            }
                            let requestid = res.data.requestid;
                            let timer = setInterval(function(){
                                layui.$.ajax({
                                    url: PROGRESS_API+'?requestid='+requestid,
                                    dataType: "json",
                                    type: "get",
                                    async: true,
                                    headers: get_header({"requestid": requestid}),
                                    success: function (res2) {
                                        if (res2.code) {
                                            layui.loading.loadRemove(1);
                                            clearInterval(timer);
                                            return layui.popup.failure(res2.msg);
                                        } else {
                                            let images = res2.data.images
                                            if(images.length>0){
                                                layui.loading.loadRemove(1);
                                                clearInterval(timer);
                                                return layui.popup.success("操作成功", function () {

                                                    layui.$('.ai_image_html').html('');
                                                    layui.$.each(images,function (i,v) {
                                                        var imgObj = new Image();                    //新建一个图片对象
                                                        imgObj.src = v;                            //将图片的src属性赋值给新建图片对象的src
                                                        imgObj.onload = function () {
                                                            var size =  new Array(imgObj.width, imgObj.height);
                                                            size[1] = parseInt(200/size[0]*size[1])
                                                            let html = '<div style="display: flex;flex-direction: column;margin-right: 20px;">';
                                                            html +='<img src="'+v+'" onclick="open_image(this);" style="width: 200px;height: '+size[1]+'px;">';
                                                            html +='<div style="display: flex;flex-direction: row; justify-content: space-between;">\n' +
                                                                '        <span>'+res2.data.tts+'秒</span>\n' +
                                                                '        <a href="javascript:;" onclick="view(\''+compile(res2.data.param)+'\')">参数预览</a>\n' +
                                                                '        <a href="javascript:;" onclick="view(\''+compile(res2.data.result)+'\')">响应预览</a>\n' +
                                                                '    </div>';
                                                            html +='</div>';
                                                            html +='<input type="hidden" name="ai_images'+parseInt(i+1)+'" value="'+v+'">';

                                                            layui.$('.ai_image_html').append(html);
                                                        }
                                                    })
                                                });
                                            }
                                        }
                                    }
                                });
                            }, 3000);
                        },
                        error:function () {
                            layui.loading.loadRemove(1);
                            return layui.popup.failure('请求失败');
                        }
                    });
                    return false;
                });
            });

            // AI会话
            layui.use(["table", "form", "common", "popup", "util"], function() {
                let common = layui.common;
                layui.$('.ai_session').click(function () {
                    let content = layui.$('textarea[name="content"]').val();
                    layer.open({
                        type: 2,
                        title: "AI会话",
                        shade: 0.1,
                        maxmin: true,
                        area: [common.isModile()?"100%":"90%", common.isModile()?"100%":"90%"],
                        content: AI_SESSION_URL + "?content=" + content
                    });
                })
            });

            function ai_image_command_change() {
                let ai_image_command = layui.$('textarea[name="ai_image_command"]').val();
                let param = {"ai_image_command":ai_image_command};
                layui.$.ajax({
                    url: AI_IMAGE_UPDATE_API,
                    type: "POST",
                    dateType: "json",
                    data: param,
                    async:false,
                    headers: get_header(param),
                    success: function (res) {
                        layui.$('input[name="ai_image_command_data"]').val(res.data.ai_image_command_data);
                    }
                });

            }

           function view(content) {
                layer.open({
                    type: 1,
                    title: "预览",
                    shade: 0.1,
                    maxmin: true,
                    area: ["900px", "500px"],
                    content: '<div style="margin: 20px;font-size: 16px;letter-spacing: 2px;">  <textarea disabled rows="23" style="height: 100%;width: 100%">'+uncompile(content)+'</textarea></div>'
                });
            }
        </script>

    </body>

</html>
